<?php

namespace MoChat\ClientNew\Action;

use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use MoChat\ClientNew\Model\ClientFollowRecord;
use MoChat\ClientNew\Model\ClientNew;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Qbhy\HyperfAuth\AuthManager;

/**
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    protected $auth;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/client-new/index", methods="post")
     */
    public function handle(): array
    {
        $params = $this->request->all();
        $user =user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $where=[];
        if (isset($user['roleId']) && $user['roleId']){

            $data_permission=Db::table('rbac_role')->where('id',$user['roleId'])->value('data_permission');
            $data_permission=$data_permission?json_decode($data_permission,true):[];
            $data_permission=empty($data_permission)?[]:reset($data_permission);
            //只看个人
            if (isset($data_permission['permissionType']) && $data_permission['permissionType']==2){
//                $employee_ids= $user['workEmployeeId'];
                $where[] = ['work_employee_id', '=', $user['workEmployeeId']];

            }
            if (isset($data_permission['permissionType']) && $data_permission['permissionType']==1){
                $department_id=Db::table('work_employee_department')->where('employee_id',$user['workEmployeeId'])->value('department_id');
                if ($department_id){
                    $employee_ids=Db::table('work_employee_department')->where('department_id',$department_id)->select('employee_id')->get();
                    $employee_ids=empty($employee_ids)?[]:array_column($employee_ids->toArray(),'employee_id');
                    $where[] = ['work_employee_id', 'in', $employee_ids];
                }
            }
        }
        if (isset($params['follow_status'])) {//30天内是否跟进
            $follows = Db::table('client_follow_record')
                ->where('followed_at', '>=',Carbon::now())
                ->select([
                    Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(client_id ORDER BY id DESC SEPARATOR ","),",",1) AS client_id'),
                    Db::raw('SUBSTRING_INDEX(GROUP_CONCAT(followed_at ORDER BY id DESC SEPARATOR ","),",",1) AS followed_at'),
                ])
                ->groupBy(['client_id'])
                ->get()
                ->toArray();
            $followId = empty($follows) ? [] : array_column($follows, 'client_id');
            if ($params['follow_status']==1){
                $where[] = ['id', 'in', $followId];
            }else{
                $where[] = ['id', 'not in', $followId];
            }
        }
        if (isset($params['b2b_user_type'])){
            $where[]=['b2b_user_type',$params['b2b_user_type']];
        }
        if (isset($params['enterprise_name'])){
            $where[]=['enterprise_name', 'LIKE', '%' . $params['enterprise_name'] . '%'];
        }
        $option = ['orderByRaw' => 'id desc', 'perPage' => 10, 'page' => $params['page'], 'pageName' => 'page'];
        $clients=(new ClientNew())->getPageList($where,['*'],$option);
        foreach ($clients['data'] as &$client){
            $user=Db::connection('b2b')->table('user')->where('unique_id',$client['uniqueId'])
                ->leftJoin('licence as l','l.id','=','user.id')->select('user.id','l.*')->first();
            $client['licence_status']='';
            if ($user){
                if ($this->checkLicence($user->BUSINESS_LICENCE)
                    ||$this->checkLicence($user->ORGANIZATION_CODE)
                    ||$this->checkLicence($user->BUSINESS_PERMIT)
                    ||$this->checkLicence($user->GOOD_SUPPLY_PRACTICE)
                    ||$this->checkLicence($user->PRACTICE_LICENSE)
                    ||$this->checkLicence($user->POWER_OF_ATTORNEY)
                ){
                    $client['licence_status']='已失效';
                }else{
                    $client['licence_status']='未失效';
                }
            }
            $count=ClientFollowRecord::query()->where('client_id',$client['id'])->where('followed_at','>=',Carbon::now()->subDays(30)->toDateTimeString())->count();
            $client['follow_count']=$count;
        }
        return $clients;
    }
    public function checkLicence($licence_date){
        if ($licence_date<Carbon::now()->toDateTimeString()){
            return false;
        }
        return true;
    }
}
